package servlet;
import java.util.List;

import javax.servlet.RequestDispatcher;

import javabean.Factory;
import javabean.user.*;


public class LoginServlet extends BaseServlet{
	/**
	 * 
	 */
	private static final long serialVersionUID = -8538076142868886263L;
	
	public void service() throws Exception{
		String uid = request.getParameter("username") ;
		String password = request.getParameter("password") ;
		String historyGo = request.getParameter("back");
		String userPic = "";
		if(uid!=null && !"".equals(uid)){
			User user = new User();
			user.setUid(uid) ;
			user.setPassword(password) ;
			try{
				if(Factory.getUserDAOInstance().isLogin(user)){
					if(Factory.getUserDAOInstance().updateActivity(user)){
						List<User> all = null;
						try{
							all = Factory.getUserDAOInstance().queryAllByUidOrEmail(uid);
						}catch(Exception ex){}
						User user2 = (User)all.get(0);
						userPic = user2.getPic();
						getSession().setAttribute("uname",user.getUname()) ;
						getSession().setAttribute("uid", user.getUid()) ;
						getSession().setAttribute("upic",userPic);
						response.getWriter().write("{\"success\":true,\"uid\":\""+user.getUid()+"\",\"uname\":\""+user.getUname()+"\",\"upic\":\""+userPic+"\",\"msg\":\"登陆成功\"}");
					}
				}
				else{
					response.getWriter().write("{\"success\":false,\"msg\":\"哎呀，用户名或密码填错了亲\"}");
				}
			}
			catch(Exception e){
				System.out.println("服务器异常");
			}
		}
		else{
			request.setAttribute("historyGo",historyGo);
			//跳转
			RequestDispatcher dispatcher = request.getRequestDispatcher("/public/login.jsp");
			dispatcher.forward(request, response) ;
		}
	}
}
